package com.lb.trac.scheduling;

import java.math.BigDecimal;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.lb.trac.pojo.Evento;
import com.lb.trac.pojo.Profilo;
import com.lb.trac.pojo.StoricoTicket;
import com.lb.trac.pojo.Tickets;
import com.lb.trac.pojo.Utenti;
import com.lb.trac.pojo.condition.TicketsFinderStatoAperto;
import com.lb.trac.service.ManageTicketService;
import com.lb.trac.service.SearchService;

public class JobAlertBean extends QuartzJobBean {

	private SearchService searchService;
	private ManageTicketService manageTicketService;
	private static final long giornoInMs = 1000 * 60 * 60 * 24;

	
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException {
		Tickets[] ticketsAperti = searchService
				.findTickets(new TicketsFinderStatoAperto());
		for (int i = 0; i < ticketsAperti.length; i++) {
			Tickets ticketAperto = ticketsAperti[i];
			long dataInserimento = ticketAperto.getDataInserimento().getTime();
			long today = new Date().getTime();
			if (today - dataInserimento > giornoInMs) {
				// spedisco la mail agli sviluppatori
				BigDecimal idProgetto = ticketAperto.getIdProgetto();
				Profilo profilo = new Profilo(new BigDecimal(2), "DEVELOPER");
				Utenti[] uv = searchService
						.findUtentiAbilitatiProgettoByProfilo(idProgetto
								.toPlainString(), profilo);
				Evento ev = new Evento();
				ev.setDataCreazione(new Date(today));
				ev.setInviato("0");
				StoricoTicket[] st = searchService
						.findMaxStoricoTicketByTicket(new StoricoTicket[0],
								ticketAperto);
				ev.setStoricoTicket(st[0]);
				ev.setTipoEvento("PROMEMORIA");
				manageTicketService.insertEventoDaInviare(ev);
			}
		}

	}


	public SearchService getSearchService() {
		return searchService;
	}


	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}


	public ManageTicketService getManageTicketService() {
		return manageTicketService;
	}


	public void setManageTicketService(ManageTicketService manageTicketService) {
		this.manageTicketService = manageTicketService;
	}

}
